import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
let cart = JSON.parse(localStorage.getItem('cart') || '[]')
let sendCat = JSON.parse(localStorage.getItem('sendCat') || '[]')
export default new Vuex.Store({
  state: {
    cart,
    isAll: true,
    sendCat
  },
  getters: {
    getAllPlic(state) {
      let p = {
        count: 0,
        plice: 0
      }
      // console.log(state.cart)
      state.cart.forEach(el => {
        if (el.isFlag) {
          p.count += el.count
          p.plice += el.count * el.CurrentPrice
        }
      })
      return p
    },
    all(state) {
      let num = 0
      state.cart.forEach(el => {
        if (el.isFlag === true) {
          num++
          console.log(num)
        }
      })
    },
    getNewPrice(state) {
      let p = {
        count: 0,
        plice: 0
      }
      state.sendCat.forEach(el => {
        if (el.isFlag) {
          p.count += el.count
          p.plice += el.count * el.CurrentPrice
        }
      })
      return p
    }
  },
  mutations: {
    addcart(state, goodsinfo) {
      var flag = false
      state.cart.some(item => {
        if (item.ID === goodsinfo.ID) {
          item.count++
          flag = true
          return true
        }
      })
      if (!flag) {
        state.cart.push(goodsinfo)
      }
      // console.log(state.cart)
      localStorage.setItem('cart', JSON.stringify(state.cart))
    },
    checke(state, index) {
      let num = 0
      state.cart[index].isFlag = !state.cart[index].isFlag
      state.cart.forEach(el => {
        if (el.isFlag === true) {
          num++
        }
      })
      state.isAll = state.cart.length === num
    },
    checkedAll(state, select) {
      state.isAll = select
      state.cart.forEach(el => {
        el.isFlag = select
      })
    },
    defaultAll(state) {
      let num = 0
      state.cart.forEach(el => {
        if (el.isFlag === true) {
          num++
        }
      })
      console.log(num)
      state.isAll = state.cart.length === num
    }
  },
  actions: {
  }
})
